"use strict";

import axios from "axios";
import { ElMessage } from "element-plus";
import { userLoadingStore } from "@/stores/pinia";
// const userLoading = userLoadingStore();
import VueCookies from "vue-cookies";
import router from "@/router";

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // 设置项目的基础路径 那么组件中只写controller中的路径即可
  baseURL: "http://localhost:8080",
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

// 要想在vue组件中使用，应该将这个导出去
export const _axios = axios.create(config);

// 请求过滤器 每次请求都携带Token
_axios.interceptors.request.use(
  function (config) {
    const token = VueCookies.get("token");
    if (token) {
      config.headers.token = token;
    }
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 请求过滤器
// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    return response;
  },
  function (error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

export const request = (url, method, params, callback) => {
  //loading.flag = true;
  const axiosCofig = {
    url,
    method,
  };
  if (method === "post") {
    // post请求追加 FormDate对象，最后转为JSON
    const formDate = new FormData();
    for (const key in params) {
      if (params[key] instanceof Array) {
        for (const i in params[key]) {
          formDate.append(key, params[key][i]);
        }
      } else {
        // 动态获取用[] , 静态获取用.
        formDate.append(key, params[key]);
      }
    }
    // 将formDate信息 打印到控制台
    console.dir(params);
    axiosCofig.data = formDate;
  } else {
    // get请求追加参数，最后转为JSON
    axiosCofig.params = params;
  }
  // userLoading.setLoading(true);
  //userLoading.setLoading(true);
  // userLoading.setLoading(true);
  _axios
    .request(axiosCofig)
    .then((response) => {
      if (response.data.code === 200) {
        // 请求成功
        if (response.data.message) {
          ElMessage.success(response.data.message);
        }
        // 调 callback 回归函数进行自定义操作
        callback(response.data.content);
      } else {
        ElMessage.error(response.data.message);
        if (response.data.code === 401) {
          // 未登入回到登入页
          router.push({
            path: "/",
          });
        }
      }
    })
    .catch((error) => {
      console.info(error);
    })
    .finally(() => {
      // userLoading.setLoading(false);
    });
};

export const get = (url, params, callback) => {
  request(url, "get", params, callback);
};

export const post = (url, params, callback, formObj = null) => {
  if (formObj) {
    formObj.value.validate((valid) => {
      if (valid) {
        request(url, "post", params, callback);
      }
    });
  } else {
    request(url, "post", params, callback);
  }
};
